let Utils = require("../../framework/js/utils");

function checkFile(self, file) {
    if (!file.name) {
        return false;
    }
    if ((file.size / 1024) > 4900 ) {
        return true;
    }
    var type = file.name.split('.').pop();
    var types = ["png", "gif", "jpg"];
    if (types.indexOf(type) < 0) {
        return false;
    }
    return true;
}

Vue.component("aui-file", {
    template: `
<div class="aui-file-upload">
   <input :id="fileinputid" name="file_upload" type="file" 
    v-if="ie9fallbackshow"
   >
  <div class="aui-file-select">                                                 
    <input v-if="!ie9fallbackshow" ref="fileinput" :id="fileinputid" type="file" /><div class="aui-file-select-name">
    <div v-if="currentFiles.length < 1">No file chosen...</div><div class="aui-file-select-name__file" v-if="currentFiles.length > 0">{{currentFiles[0].name}}</div>
</div><div class="aui-file-select-button">请选择文件</div>
  </div>  
</div>    
    `,
    props: {
        value: {
            required: true
        }
    },
    data() {
        var ret = {};
        ret.currentFiles = [];
        ret.fileinputid = Utils.uniqueSelector("fileinput_");

        ret.ie9fallbackshow = false;

        ret.s = 1;

        if (fuckIE9) {
            ret.ie9fallbackshow = true;
        }

        return ret;
    },
    mounted() {
        var self = this;
        self.anuElement = $(self.$refs.fileinput);

        if (self.value) {
            self.currentFiles = [{
                name: self.value
            }];
        }

        self.$emit("beforeshow", self);

        var iframe = false;
        if(fuckIE9){
            iframe = true;
        }

        var options = {
            url: "",
            dataType: 'text',
            singleFileUploads: true,
            paramName: "file",
            sequentialUploads: true,
            autoUpload: false,
            formData: {}
        };

        self.globalfilesubmit = {};

        var file_id =  Utils.uniqueSelector("fileinput_");

        if (fuckIE9) {
            window.ssdsdsdsdsds = $("#" + self.fileinputid);
            ssdsdsdsdsds.uploadify({
                'auto'     : false,
                'fileTypeDesc' : 'Image Files',
                'fileTypeExts' : '*.gif; *.jpg; *.png',
                'fileObjName' : 'file',
                'fileSizeLimit' : '5MB',
                'formData'     : {
                    'timestamp' : new Date().valueOf(),
                    'token': rootcontroller.tokenManager.getToken()
                },
                'swf'      : window.globalUploadifyPath,
                // 'uploader' : 'uploadify.php',
                // 'uploader' : 'http://192.168.10.26:7001/api/save',
                // 'uploader' : rootcontroller.getUploadUrl() + "&k=" + aui.Utils.uniqueSelector("fileinput_"),
                'uploader': rootcontroller.getUploadUrl(),
                width: self.$el.offsetWidth,
                height: self.$el.offsetHeight - 15,
                onSelect : function(file) {
                    self.currentFiles = [{
                        name: file.name
                    }];
                    self.$emit("changefilesuccess", {
                        upload() {
                            ssdsdsdsdsds.uploadify("upload");
                        }
                    });
                    self.$emit("input", self.currentFiles[0].name);
                },
                onSelectError: function (file, errorCode) {
                    self.$emit("changefileerror", file);
                },
                onUploadSuccess(file, data, response) {
                    self.$emit("success", file, data, response);
                }
            });
        } else {
            var uploader = $(self.$refs.fileinput).fileupload(options);
            uploader.on("fileuploadadd", function(evt, data) {
                console.log("Add file");

                data.url = rootcontroller.getUploadUrl() + "&k=" + file_id;

                self.globalfilesubmit = data;
                window.globalfilesubmit = data;

                data.file_id = file_id;

                self.handleFileChange(evt, data);

                self.$emit("fileuploadadd", evt, data);
            });
            uploader.on("fileuploadstart", function(evt, data) {
                console.log("upload start");

                self.$emit("fileuploadstart", evt, data);
            });
            uploader.on("fileuploaddone", function(evt, data) {
                console.log("upload done");
                var file = {};
                self.$emit("success", data.files[0], data.result, data);
            });
            uploader.on("fileuploadfail", function(evt, data) {
                console.log("upload failed");

                self.$emit("fileuploadfail", evt, data);
            });
            uploader.on("fileuploadchange", function(evt, data) {
                console.log("change");
            });
        }
        if (fuckIE9 || isIE10) {
            self.anuElement.mousedown(function() {
                $(this).trigger('click');
            })
        }
    },
    beforeDestroy() {
        var self = this;
        self.$emit("savefiles", self.currentFiles);
    },
    methods: {
        handleFileChange(e, data) {
            var self = this;
            if (data && data.files && data.files.length > 0) {
                self.currentFiles = data.files;
                var isok = checkFile(self, data.files[0]);
                if (isok) {
                    self.$emit("changefilesuccess", self);
                    self.$emit("input", self.currentFiles[0].name);
                }  else {
                    self.$emit("changefileerror", data.files[0]);
                }
            }

            // if (fuckIE9) {
            // } else {
            //     if (e.target.value) {
            //         if (e.target.files && e.target.files.length > 0) {
            //             var isok = checkFile(self, e.target.files[0]);
            //             if (isok) {
            //                 self.currentFiles = e.target.files;
            //                 self.$emit("changefilesuccess", self);
            //                 self.$emit("input", self.currentFiles[0].name);
            //             } else {
            //                 self.$emit("changefileerror", e.target.files[0]);
            //             }
            //         } else {
            //             self.currentFiles = [{
            //                 name: e.target.value
            //             }];
            //         }
            //     }
            // }
        },
        checkFile(file){
            return checkFile(file)
        },
        upload() {
            var self = this;
            if (self.globalfilesubmit.submit) {
                self.globalfilesubmit.submit();
            } else {
                self.$emit("uploaderror");
            }
        }
    }
});